package com.restfinder.user.service;

import java.io.Serializable;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(rollbackFor=Exception.class)
@Slf4j
public class AuthenticationService implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager authenticationManager;
	
	public boolean login(String login, String password) {
			try{
					Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(login, password));
				if(authenticate.isAuthenticated()){
					SecurityContextHolder.getContext().setAuthentication(authenticate);
					return true;
				}
			}catch(Exception e){
				log.error("Chuj",e);
				e.printStackTrace();
				return false;
			}
		return false;
	}
	
	public static String getAuthenticatedUsername(){
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username;
        if (obj instanceof UserDetails) {
                username = ((UserDetails) obj).getUsername();
        } else {
                username = obj.toString();
        }
        return username;
	}
}